package org.dreamwork.jasmine2.web.client;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 12-4-26
 * Time: 上午11:28
 */
public class Version {
    public int major, minor;
    public Integer reversion, build;

    public static final Version UNKNOWN = new Version (-1, -1) {
        @Override
        public String toString () {
            return "Unknown";
        }
    };

    private static final Pattern p = Pattern.compile ("[\\d]|^[\\d]+([\\d\\.]*)[\\d]+$");

    public Version (int major, int minor) {
        this (major, minor, null, null);
    }

    public Version (int major, int minor, Integer reversion) {
        this (major, minor, reversion, null);
    }

    public Version (int major, int minor, Integer reversion, Integer build) {
        this.major = major;
        this.minor = minor;
        this.reversion = reversion;
        this.build = build;
    }

    public Version (String text) {
        String version = text.replace ('_', '.').replaceAll ("[^\\d\\.]", "");
        Matcher m = p.matcher (version);
        if (!m.matches ())
            throw new IllegalArgumentException ("Illegal version expression, the expression looks like '[\\d]|^[\\d]+([\\d\\.]*)[\\d]+$'");

        if (version.indexOf ('.') == -1) {
            major = Integer.parseInt (version);
            return;
        }

        String[] parts = version.split ("\\.");
        major = Integer.parseInt (parts [0]);
        if (parts.length > 1)
            minor = Integer.parseInt (parts [1]);
        if (parts.length > 2)
            reversion = Integer.valueOf (parts [2]);
        if (parts.length > 3)
            build = Integer.valueOf (parts [3]);
    }

    @Override
    public String toString () {
        String text = major + "." + minor;
        if (reversion != null) {
            text += "." + reversion;
            if (build != null) text += "." + build;
        }
        return text;
    }
}